package com.zwb.demo.easyweb.common;

import com.zwb.demo.easyweb.common.entity.ValueEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
@SuppressWarnings("all")
public class EnumConvertFactory implements ConverterFactory<Integer, ValueEnum> {

    @Override
    public <T extends ValueEnum> Converter<Integer, T> getConverter(Class<T> aClass) {
        return new IntegerToEnum<>(aClass);
    }

    class IntegerToEnum<E extends ValueEnum> implements Converter<Integer, E> {
        private final Class<E> enumType;

        IntegerToEnum(Class<E> enumType) {
            this.enumType = enumType;
        }

        @Override
        public E convert(Integer integer) {
            E e = (E) ValueEnum.valueToEnum(enumType, integer);
            if (e == null) {
                throw new IllegalArgumentException("No element matches " + e);
            }
            return e;
        }
    }
}
